import React, { Suspense } from 'react';
import { useLocation } from 'react-router';
import PropTypes from 'prop-types';
import { isRoot } from 'stripes-config';

import { LoadingView, Loading } from '@folio/stripes-components';

import { ModulesContext } from './ModulesContext';
import { GlobalConsumer } from '@jiatuan/hooks';

import { packageName } from './constants';
import {
  BadRequestScreen,
  NoPermissionScreen,
  ResetPasswordNotAvailableScreen,
  TitledRoute,
} from './components';

import AppRoutes from './AppRoutes';

const propTypes = {
  stripes: PropTypes.shape({
    clone: PropTypes.func.isRequired,
    epics: PropTypes.object,
    hasPerm: PropTypes.func.isRequired,
    logger: PropTypes.object.isRequired,
  }).isRequired,
};

function ModuleRoutes({ stripes }) {
  const location = useLocation();

  return (
    <GlobalConsumer>
      {({ state }) => (
        <ModulesContext.Consumer>
          {(modules) => {
            if (!Array.isArray(modules.app) && modules.length < 1) {
              throw new Error('At least one module of type "app" must be enabled.');
            }

            const isRawApp = !isRoot && !window.__POWERED_BY_QIANKUN__;

            let isValidRoute;

            if (isRawApp) {
              isValidRoute = modules.app.some(module => location.pathname.startsWith(`${module.route}`));
            } else if (isRoot) {
              isValidRoute = state.apps.some(module => location.pathname.startsWith(`${module?.activeRule}`));
            } else {
              isValidRoute = modules.app.some(module => location.pathname.startsWith(`${module.route}`));
            }

            if (!isValidRoute) {
              const isResetPasswordRoute = location.pathname.startsWith('/reset-password');

              return isResetPasswordRoute
                ? (
                  <TitledRoute
                    name="notFound"
                    component={<ResetPasswordNotAvailableScreen />}
                  />
                ) : (
                  <TitledRoute
                    name="notFound"
                    component={
                      // (isRoot && !window.__POWERED_BY_QIANKUN__) ? (
                      //   <div style={{
                      //     height: '100%',
                      //     display: 'flex',
                      //     justifyContent: 'center',
                      //     alignItems: 'center'
                      //   }}>
                      //     <Loading size="xlarge" />
                      //   </div>
                      // ) : (
                        <BadRequestScreen />
                      // )
                    }
                  />
                );
            }

            let currentModule;

            if (isRawApp) {
              currentModule = modules.app.find(module => location.pathname.startsWith(`${module.route}`));
            } else if (isRoot) {
              currentModule = state.apps.find(module => location.pathname.startsWith(`${module.activeRule}`));
            } else {
              currentModule = modules.app.find(module => location.pathname.startsWith(`${module.route}`));
            }

            const moduleName = isRawApp
              ? currentModule?.module?.replace(packageName.PACKAGE_SCOPE_REGEX, '')
              : currentModule.name;

            if (!stripes.hasPerm(`module.${moduleName}.enabled`)) {
              return (
                <TitledRoute
                  name="noPermission"
                  component={<NoPermissionScreen />}
                />
              );
            }

            return (
              <Suspense fallback={<LoadingView />}>
                <AppRoutes modules={modules} stripes={stripes} />
              </Suspense>
            );
          }}
        </ModulesContext.Consumer>
      )}
    </GlobalConsumer>
  );
}

ModuleRoutes.propTypes = propTypes;

export default ModuleRoutes;

// this might be handy at some point:
//
// import React, { useContext, useMemo } from 'react';
// import { Route, useLocation } from 'react-router-dom';
// import { isQueryResourceModule } from './locationService';
//
// export const useModules = () => useContext(ModulesContext);
//
// export const useCurrentApp = () => {
//   const modules = useModules();
//   const location = useLocation();
//
//   const memoizedApp = useMemo(() => {
//     const { app, settings } = modules;
//     return app.concat(settings).find(m => isQueryResourceModule(m, location));
//   }, [location, modules]);
//
//   return memoizedApp;
// };
